const lists = {
    'musiclrc': './LRC/老人と海.lrc',
    background:'',
    backcolor: '#000000',
    fontposition: 'center',
    fontcolor: '#ffffff',
    progresscolor: '#ffffff',
    hovercolor: '#ffffff',
    visualcolor: '#ffffff',
}
const audioPlayer = document.getElementById("audioPlayer")
const music_info = document.querySelector(".music-info")
const lrcContainer = document.querySelector(".lrc")
const start = document.querySelector('.start')

const progressContainer = document.querySelector('.progress')
const progressBar = progressContainer.querySelector('.progress-bar')
const hoverbar = document.querySelector('.hover-bar')
const hovertime = document.querySelector('.hover-time')

const debugele = document.querySelector('.debug')
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

let analyser
let dataArray

const { width, height } = canvas


let lrcs = []

/**
 * 
 * @param {*string} time 
 * @returns 工具函数格式化时间
 */
function formatTime(time) {
    const minutes = Math.floor(time / 60)
    const seconds = Math.floor(time % 60)
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

window.addEventListener('keydown', (e) => {
    console.log(e.key)

    if (e.key == " ") {
        if (audioPlayer.paused) {
            audioPlayer.play()
            music_info.classList.remove('over')
            music_info.classList.add("active")
            music_info.innerHTML = "Playing Press 'H' to hide debug info"
            start.style.display = "none"
        } else {
            audioPlayer.pause()
            music_info.classList.remove("active")
            music_info.innerHTML = "Paused. Press 'Space' to Play"
        }
    } else if (e.key == "h") {
        if (debugele.classList.contains('hide')) {
            debugele.classList.remove('hide')
            music_info.classList.remove('hide')
        } else {
            debugele.classList.add('hide')
            music_info.classList.add('hide')
        }
    }
})

progressContainer.addEventListener('click', (e) => {
    const rect = progressContainer.getBoundingClientRect()
    const ratio = (e.clientX - rect.left) / rect.width
    audioPlayer.currentTime = audioPlayer.duration * ratio
})

progressContainer.addEventListener('mousemove', (e) => {
    const rect = progressContainer.getBoundingClientRect()
    const progress_t = Math.max(0, Math.min(rect.width, e.clientX - rect.left))
    hoverbar.style.width = `${progress_t}px`
    // 更新鼠标悬停时间
    if (audioPlayer.duration) {
        const time = audioPlayer.duration * (progress_t / rect.width)
        hovertime.textContent = formatTime(time)
        hovertime.style.left = `${e.clientX + hovertime.offsetWidth / 2}px`
        hovertime.style.display = 'block'
    }
})

progressContainer.addEventListener('mouseleave', () => {
    hovertime.style.display = 'none'
    hoverbar.style.width = '0'
})

/**
 * 
 * @param {*string} lrc
 * LRC解析函数 
 */
function parseLRC(lrc) {
    // 数据处理
    const lines = lrc.split('\n')
    const pattern = /\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/
    const lyrics = []
    for (let i = 0; i < lines.length; i += 2) {
        const jpMatch = pattern.exec(lines[i])
        // 使用正则表达式 pattern 来匹配 lines[i]。lines[i] 是一个形如 [mm:ss.xx]lyrics 的字符串。
        // 其中 mm 是分钟，ss 是秒，xx 是毫秒，lyrics 是歌词。
        // pattern.exec 返回一个数组，其中第一个元素是匹配的整个字符串(即 [mm:ss.xx]lyrics),
        // 后面的元素是正则表达式中的捕获组(即 mm、ss、xx 和 lyrics).
        const cnMatch = pattern.exec(lines[i + 1])
        if (jpMatch && cnMatch) {
            const time = parseInt(jpMatch[1]) * 60 + parseInt(jpMatch[2]) + parseInt(jpMatch[3]) / 1000
            lyrics.push({
                time: time,
                jp: jpMatch[4].trim(), // trim() 方法用于删除字符串两端的空白字符
                cn: cnMatch[4].trim()
            })
        }
    }
    return lyrics.sort((a, b) => a.time - b.time)
}

/**
 * 更新歌词信息
 * @returns 
 */
function updateLyrics() {
    const currentTime = audioPlayer.currentTime
    const currentLyric = lrcs.find((lyric, index) => {
        const nextLyric = lrcs[index + 1]
        return currentTime >= lyric.time && (!nextLyric || currentTime < nextLyric.time)
    })
    if (currentLyric) {
        // lrcContainer.innerHTML = ''
        // 这样不太行 添加上去会一直更新
        const existingLyrics = lrcContainer.querySelectorAll('span')

        const currentJPElement = Array.from(existingLyrics).find(
            element => element.textContent === currentLyric.jp)
        // Array.from(existingLyrics) 将 
        // existingLyrics 转换为一个真正的数组，这样你就可以使用数组的方法，
        // 比如 find。
        // console.log(currentJPElement);

        // 如果当前歌词已经显示，则不做处理
        if (currentJPElement) return
        existingLyrics.forEach(span => span.remove())

        console.log(currentLyric)

        // 添加日语歌词
        const jpLyric = document.createElement('span')
        jpLyric.textContent = currentLyric.jp
        jpLyric.classList.add('jp')
        lrcContainer.appendChild(jpLyric)
        jpLyric.classList.add('active')

        // 添加中文歌词
        const cnLyric = document.createElement('span')
        cnLyric.textContent = currentLyric.cn
        cnLyric.classList.add('cn')
        lrcContainer.appendChild(cnLyric)
        cnLyric.classList.add('active')
    }
}

/**
 * 更新播放进度条
 */

function updateProgress() {
    const progress = (audioPlayer.currentTime / audioPlayer.duration) * 100
    progressBar.style.width = `${progress}%`
}

/**
 * 初始化可视化
 */
function init() {
    const audCtx = new AudioContext()
    const source = audCtx.createMediaElementSource(audioPlayer)
    analyser = audCtx.createAnalyser()
    source.connect(analyser)
    analyser.connect(audCtx.destination)
    analyser.fftSize = 64
    dataArray = new Uint8Array(analyser.frequencyBinCount) // 获取分析数据结果
}
init()

/**
 * 
 * @returns 
 * 绘制可视化
 */
function draw() {
    if (audioPlayer.paused) return
    requestAnimationFrame(draw)
    ctx.clearRect(0, 0, width, height)
    analyser.getByteFrequencyData(dataArray)
    let len = dataArray.length
    len = len / 2
}


// 加载LRC文件
fetch(lists.musiclrc).then(response => response.text()).then(data => {
    lrcs = parseLRC(data)
    // 开始监听时间更新
    audioPlayer.addEventListener('timeupdate', musicplaying)
    audioPlayer.addEventListener('ended', () => {
        music_info.innerHTML = "Music is Over. Pause to play again."
        music_info.classList.add('over')
    })
}
).catch(error => console.error('Error loading lyrics:', error))
function musicplaying() {
    updateLyrics()
    updateProgress()
}
